package Control;

import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

import GUI.*;
import Entity.*;

/**
 * Controls the instance of login
 * This class sends and gets data from the server of the users exist in the system 
 * and display it on the panel.
 * @author Aviat
 *
 */ 
public class LoginControl {
	
	private Login logInPanel;
	private MsgPackage LonInMsg;
	private User user;
	
	/**
	 * the constructor
	 */
	public LoginControl(){
		logInPanel = new Login();
		LonInMsg= new MsgPackage();
		user= new User();
	}

	/**
	 * This method sends the user name and password 
	 *  The server sends an answer (received from query from database) 
	 *  and the control display it in a message
	 *  @ return boolean
	 */	
	public boolean loginReq_pressed(){
		String uID = logInPanel.get_userName().getText().toString();
		String pass = logInPanel.get_password().getText().toString();
		
		if(uID==null||pass==null){
			JOptionPane.showMessageDialog(null, "Not all the fileds all the fill", "ERROR", JOptionPane.ERROR_MESSAGE);
			return false;	
		}
		else{
			user.setUserName(Integer.parseInt(uID));
			user.setPassword(pass);
			LonInMsg.setObject(user);
			LonInMsg.setOp_code(OP_CODE.LOGIN);
			ScreenManager.getConnection().accept(LonInMsg);
			
			Object o = ScreenManager.getConnection().cclient.getMessage();

			user = (User)o;
	    	if(user.getIs_exists()){
	    		ScreenManager.getUserLogged().setUserName(user.getUserName());
	    		ScreenManager.getUserLogged().setPassword(user.getPassword());
	    		ScreenManager.getUserLogged().setPrivilage(user.getPrivilage());
	    		System.out.println(ScreenManager.getUserLogged().getUserName());
	    	}
			else if(!(user.getIs_exists())) {
				if(user.getPassword().equals(""))
					JOptionPane.showMessageDialog(null, "Wrong password, enter details again", "ERROR", JOptionPane.ERROR_MESSAGE);
				else
					JOptionPane.showMessageDialog(null, "User does not exsits!", "ERROR", JOptionPane.ERROR_MESSAGE);
				return false;
			}
		}
		return true;
	}



	/**
	 * @return the user
	 */
	public User getUser() {
		return user;
	}

	/**
	 * @return the logInPanel
	 */
	public Login getlogInPanel(){
		return logInPanel;
	}
	
}//end LoginControl function